package com.chen.boot.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.boot.config.GlobalListener;
import com.chen.boot.config.GlobalType;
import com.chen.boot.db.entity.ContactsInfo;
import com.chen.boot.db.mapper.ContactsInfoMapper;
import com.chen.im.view.ContactsList;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Description
 * @Author Pengwei
 * @CreatDate 2021/11/17 14:31
 */
@Service
public class ContactsInfoService extends ServiceImpl<ContactsInfoMapper, ContactsInfo> {

    public void updateContactsBySocket(String ip, Long id, String name) {
        //检查该用户是否已经在显示列表中了
        ContactsInfo viewItem = ContactsList.items.stream().filter(v -> v.getId().equals(id) && v.getIp().equals(ip)).findAny().orElse(null);
        if (viewItem != null) {
            viewItem.setLastCheckTime(LocalDateTime.now());
            ContactsList.updateName(viewItem, name);
            return;
        }
        ContactsInfo contactsInfo = this.getById(id);
        if (contactsInfo == null) {
            contactsInfo = new ContactsInfo();
            contactsInfo.setId(id);
            contactsInfo.setName(name);
            contactsInfo.setHideBol(false);
            save(contactsInfo);
            GlobalListener.instance.listenerEvent(GlobalType.saveContacts, contactsInfo);
        }

        if (!contactsInfo.getName().equals(name)) {
            contactsInfo.setName(name);
            save(contactsInfo);
        }
        contactsInfo.setLastCheckTime(LocalDateTime.now());
        contactsInfo.setIp(ip);
        ContactsList.updateItems(contactsInfo);
    }
}
